package com.xsq.activity;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.POSD.controllers.PrinterController;
import com.alibaba.fastjson.JSON;
import com.demo.activity.BuzzerControllerActivity;
import com.demo.activity.PrinterControllerActivity;
import com.demo.activity.TestActivity;
import com.demo.activity.nfc.NFCController.NFCControllerActivity;
import com.xsq.BaseActivity;
import com.xsq.Constant;
import com.xsq.KeyBoardListener;
import com.xsq.PosMainActivity;
import com.xsq.R;
import com.xsq.URLConstant;
import com.xsq.bo.ServerInfos;
import com.xsq.util.HttpInterface;
import com.xsq.util.ServerUtils;

/**
 * 系统设置页面,展示系统功能菜单
 * @author Administrator
 *
 */
@SuppressLint({ "SetJavaScriptEnabled", "HandlerLeak" })
public class DeviceSetActivity extends BaseActivity {

	private PrinterController printerController = null;

	private String initSetType;
	
	private static final int GO_HOME = 1000;
	private static final int GO_DEMO_PRINT = 1001;
	private static final int GO_DEMO_FM = 1002;
	private static final int GO_DEMO_NFC = 1003;
	private static final int GO_DEMO_CONTROL = 1004;
	
	private static final int SHOW_SUBMIT_POS_RESULT = 1009;
	private static final int SHOW_SUBMIT_TX_RESULT = 1008;
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GO_HOME:
				loadHome();
				break;
			case GO_DEMO_PRINT:
				loadDemoPrintPage();
				break;
			case GO_DEMO_FM:
				loadDemoFmPage();
				break;
			case GO_DEMO_NFC:
				loadDemoNfcPage();
				break;
			case GO_DEMO_CONTROL:
				loadDemoControlPage();
				break;	
				
				
			case SHOW_SUBMIT_POS_RESULT:
				showSubmitPosResult(msg);
				break;	
			case SHOW_SUBMIT_TX_RESULT:
				showSubmitTxResult(msg);
				break;
					
			}
		}
	};

	
	public void showSubmitPosResult(Message msg){
		
		hide_loading();
		String rs = msg.getData().getString("rs");
		String call = "javascript:showSubmitPosRs('"+rs+"');";
		
		myWebView.loadUrl(call);
	}
	public void showSubmitTxResult(Message msg){
		
		hide_loading();
		String rs = msg.getData().getString("rs");
		String call = "javascript:showSubmitTxRs('"+rs+"');";
		
		myWebView.loadUrl(call);
	}
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.set_main);
		
		if (null == printerController) {
			printerController = PrinterController.getInstance(this);
		}
		int flag = printerController.PrinterController_Open();
		if (flag == 0) {
			//Toast.makeText(this, "connect_Success", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "打印机无法连接,请重试", Toast.LENGTH_SHORT).show();
			
		}
	
		
		preferences = getSharedPreferences(Constant.CACHE_XSQ_POS, MODE_PRIVATE);
		editor = preferences.edit();
		
		serverUtils = new ServerUtils(preferences, editor);
		hi = new HttpInterface(serverUtils);
		
		
		Intent intent = getIntent();
        String setTypeStr = intent.getStringExtra("setType");
        if(setTypeStr!=null && !setTypeStr.equals("")){
        	initSetType = setTypeStr;
        }
		
		myWebView = (WebView) findViewById(R.id.webview);

		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(false); // 支持缩放
		webSettings.setBuiltInZoomControls(false); // 显示放大缩小
		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 解决缓存问题
		myWebView.addJavascriptInterface(new DeviceOp(this), "appControl");
		myWebView.setWebViewClient(new MyWebViewClient());
		myWebView.setWebChromeClient(new MyWebChromeClient());
		
		myWebView.loadUrl(URLConstant.PAGE_SYS_SET);
		KeyBoardListener.getInstance(this).init();
	}

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			AlertDialog.Builder b2 = new AlertDialog.Builder(DeviceSetActivity.this).setTitle("提示：").setMessage(message)
					.setPositiveButton("ok", new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b2.setCancelable(false);
			b2.create();
			b2.show();
			return true;
		}
	}

	private class MyWebViewClient extends WebViewClient {
		/**
		 * 如果希望点击链接由自己处理，而不是新开Android的系统browser中响应该链接。
		 * 给WebView添加一个事件监听对象（WebViewClient)并重写其中的一些方法：
		 * shouldOverrideUrlLoading：对网页中超链接按钮的响应。当按下某个连接时
		 * WebViewClient会调用这个方法，并传递参数：按下的url。比如当webview内嵌
		 * 网页的某个数字被点击时，它会自动认为这是一个电话请求，会传递url：tel:123,
		 * 如果你不希望如此可通过重写shouldOverrideUrlLoading函数解决
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 当开启新的页面的时候用webview来进行处理而不是用系统自带的浏览器处理
			// 互联网用：webView.loadUrl("http://www.google.com");
			// 本地文件用：webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放
			view.loadUrl(url);
			return true;
		}

		/**
		 * 载入页面完成的事件
		 **/
		@Override
		public void onPageFinished(WebView view, String url) {
			// 获取网页内容
			// view.loadUrl("javascript:window.local_obj.showSource"+
			// "('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			super.onPageFinished(view, url);
			if(initSetType!=null){
				String call = "javascript:initSet('"+initSetType+"');";
				view.loadUrl(call);
			}
		}

		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
			Toast.makeText(getApplicationContext(), "加载失败,请联系管理员", Toast.LENGTH_LONG).show();
		}
	}

	private void loadHome() {
		Intent intent = new Intent(this, PosMainActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadDemoPrintPage() {
		Intent intent = new Intent(this, PrinterControllerActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadDemoFmPage() {
		Intent intent = new Intent(this, BuzzerControllerActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadDemoNfcPage() {
		Intent intent = new Intent(this, NFCControllerActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadDemoControlPage() {
		Intent intent = new Intent(this, TestActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
         if(keyCode == KeyEvent.KEYCODE_BACK){
        	 loadHome();
             return true;
         }
         return super.onKeyDown(keyCode, event);
     }
	
	private class DeviceOp {

		private Context mContext;

		public DeviceOp(Context c) {
			mContext = c;
		}

		@JavascriptInterface
		public String doTest() {
			Toast.makeText(mContext, "test ... test", Toast.LENGTH_SHORT).show();
			return "1";
		}
		
		
		
		
		
		@JavascriptInterface
		public String doTxConfig(final String serverIp1,final String port1,final String serverIp2,final String port2) {

			try{
				
				show_loading("正在验证服务器可用性并保存...");
				Constant.threadPoolExecutor.execute(new Runnable() {
					
					@Override
					public void run() {
						
						String rs = "";
						if (serverIp1 == null || serverIp1.trim().equals("")  ||port1 == null || port1.trim().equals("") ) {
							//必选参数为空或者参数格式不对
							rs =  "-1";
						} else {
							boolean hasBak = false;
							if(serverIp2!=null && !serverIp2.equals("") && port2!=null && !port2.equals("")  &&  !(serverIp2.equals(serverIp1) && port1.equals(port2))){
								hasBak = true;
							}
							//参数格式验证
							
							serverUtils.removeAllServer();
							
							String server = serverIp1+":"+port1;
							//数据后台验证
							Map<String,Object> testResult = hi.testServer(server, "test", "test");
							String validResult = "";
							
							validResult+=String.valueOf(testResult.get("is_success"));
							
							//保存进入缓存
							serverUtils.setServer(server, String.valueOf(testResult.get("is_success")));
							
							if(hasBak){
								validResult+=",";
								String server2 = serverIp2+":"+port2;
								//数据后台验证
								Map<String,Object> testResult2 = hi.testServer(server2, "test", "test");
								validResult+=String.valueOf(testResult2.get("is_success"));
								
								serverUtils.setServer(server2, String.valueOf(testResult.get("is_success")));
							}
							
							rs =  validResult;
							
							Message message = new Message();
							message.what = SHOW_SUBMIT_TX_RESULT;
							Bundle bundle = new Bundle();
							bundle.putString("rs", rs);
							message.setData(bundle);
							
							mHandler.sendMessage(message);
						}
						
					}
				});
				
			
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String doPosConfig(final String posno,final String winno) {

			try{
				show_loading("正在提交数据...");
				
				
				Constant.threadPoolExecutor.execute(new Runnable() {
					
					@Override
					public void run() {
						
						String rs = "";
						if (posno == null || posno.trim().equals("") || winno == null || winno.trim().equals("") ) {
							//必选参数为空
							rs =  "-1";
						} else {
							
							//参数格式验证
						
							//数据后台验证
							Map<String,Object> result = hi.validatePosParam(posno, getDeviceId(), winno);
							
							if(String.valueOf(result.get("is_success")).equals("1")){
								editor.putString(Constant.CACHE_POSNO, posno);
								editor.putString(Constant.CACHE_WINNO, winno);
								
								editor.putString(Constant.CACHE_WINNAME, String.valueOf(result.get("winname")));
								editor.putString(Constant.CACHE_MERCHANT, String.valueOf(result.get("merchantname")));
								editor.putString(Constant.CACHE_XFXX, String.valueOf(result.get("xfxe")));
								
								editor.commit();
							}
							if(String.valueOf(result.get("is_success")).equals("0") ){
								rs =  String.valueOf(result.get("error_msg"));
							}else{
								rs = String.valueOf(result.get("is_success"));
							}
							
							
						}
						
						
						Message message = new Message();
						message.what = SHOW_SUBMIT_POS_RESULT;
						Bundle bundle = new Bundle();
						bundle.putString("rs", rs);
						message.setData(bundle);
						
						mHandler.sendMessage(message);
					}
				});
				
				
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String srchPosConfig() {
			try {
				String posno = getPosNo();
				String winno = getWinNo();
				return "1," + posno + "," + winno;
			} catch (Exception e) {
				return "-100";
			}
		}
		
		
		@JavascriptInterface
		public String doUpdatePwd(String oldpwd,String newpwd) {

			try{
				if (oldpwd==null || newpwd==null) {
					//必选参数为空
					return "-1";
				} else {
					//格式验证
	
					if(!getSysAdmin().equals(oldpwd)){
						return "旧密码不对";
					}else{
						//修改新密码
						editor.putString(Constant.CACHE_PWD_SYSADMIN, newpwd);
						editor.commit();
						
						return "1";
					}
				
				}
			}catch(Exception e){
				return "-1";
			}
		}
		
		
		/**
		 * 
		 * @return
		 */
		@JavascriptInterface
		public String toPrint() {
			try{
				mHandler.sendEmptyMessage(GO_DEMO_PRINT);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		/**
		 * 打印机编码设置
		 * @return
		 */
		@JavascriptInterface
		public String to_printer() {
			try{
				
				
				
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		/**
		 * 
		 * @return
		 */
		@JavascriptInterface
		public String toHome() {
			try{
				mHandler.sendEmptyMessage(GO_HOME);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		

		/**
		 * 蜂鸣测试页面
		 * @return
		 */
		@JavascriptInterface
		public String toFm() {
			try{
				mHandler.sendEmptyMessage(GO_DEMO_FM);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		/**
		 * NFC测试页面
		 * @return
		 */
		@JavascriptInterface
		public String toNfc() {
			try{
				mHandler.sendEmptyMessage(GO_DEMO_NFC);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		@JavascriptInterface
		public String  getCurCardType() {
			
			try{
				String cardType = getCardType();
				return cardType;
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String  setCurCardType(String cardmode) {
			
			try{
				if(cardmode==null || Constant.CARD_READ_MODE.get(cardmode)==null){
					return "-1";
				}
				
				
				editor.putString(Constant.CACHE_CARDTYPE, cardmode);
				editor.commit();
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String printTestByCode(String ctype){
			
			if(ctype==null || (!ctype.equals("0") && !ctype.equals("1"))){
				return "-1";
			}
			try{
				printerController.PrinterController_reset();
				printerController.PrinterController_PrinterLanguage(0);
				printerController.PrinterController_Take_The_Paper(1);// 打印机走纸
				printerController.PrinterController_Set_Center();
				printerController.PrinterController_Print("--------------------------".getBytes());
				printerController.PrinterController_Linefeed();// 换行

				
				// 标题加粗居中
				printerController.PrinterController_Font_Bold();
				//printerController.PrinterController_Set_Center();
				if(ctype.equals("0")){
					printerController.PrinterController_PrinterLanguage(2);
					printerController.PrinterController_Print("鑫三强消费POS机".getBytes("GB2312"));// 单据头
				}else if(ctype.equals("1")){
					printerController.PrinterController_PrinterLanguage(0);
					printerController.PrinterController_Print("鑫三强消费POS机".getBytes());// 单据头
				}
				printerController.PrinterController_Linefeed();// 换行
				printerController.PrinterController_Linefeed();// 换行
				printerController.PrinterController_Print("--------------------------".getBytes());
				printerController.PrinterController_Linefeed();// 换行
				printerController.PrinterController_Linefeed();// 换行
				printerController.PrinterController_Linefeed();// 换行
				printerController.PrinterController_Take_The_Paper(1);// 打印机走纸
				
				return "1";
			}catch(Exception e){
				e.printStackTrace();
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String savePrintCode(String ctype){
			try{
				
				editor.putString(Constant.CACHE_PRINTER_CODE, ctype);
				editor.commit();
				
				return "1";
			}catch(Exception e){
				e.printStackTrace();
				return "-100";
			}
		}
		
		
		@JavascriptInterface
		public void showPrintMode() {

			AlertDialog.Builder builder = new AlertDialog.Builder(mContext, android.R.style.Theme_Holo_Light_Dialog);
			// builder.setIcon(R.drawable.ic_launcher);
			builder.setTitle("选择消费后是否打印发票");
			// 指定下拉列表的显示数据
			final String[] modes = { "不打印发票", "打印一张发票", "打印二张发票" };
			// 设置一个下拉的列表选择项
			builder.setItems(modes, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(mContext, "选择的内容为：" + modes[which], Toast.LENGTH_SHORT).show();
					
					editor.putString(Constant.CACHE_CONSUME_PRINT_MODE, String.valueOf(which));
					editor.commit();
				}
			});	
			
			builder.show();
		}
		
		@JavascriptInterface
		public String saveConsumeMode(String print,String pwd){
			
			try{
				editor.putString(Constant.CACHE_CONSUME_PRINT_MODE, String.valueOf(print));
				editor.putString(Constant.CACHE_CONSUME_PWD_MODE, String.valueOf(pwd));
				editor.commit();
				
				return "1";
				
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		
		/**
		 * 
		 * @param type all=全部 1=上位机  2=系统参数  3=其他设置
		 * @return
		 */
		@JavascriptInterface
		public String srchSysInfo(String type){
			
			Map<String,Object> info = new HashMap<String, Object>();
			try{
				
				if(type.equals("1") || type.equals("all")){
					//上位机信息
					String serverInfo = getServerInfo();
					if(serverInfo==""){
						info.put("oneServer", "未设置");
						info.put("twoServer", "未设置");
						
						info.put("serverIp1", "");
						info.put("serverPort1", "");
						info.put("serverIp2", "");
						info.put("serverPort2", "");
					}else{
						ServerInfos infos = JSON.parseObject(serverInfo, ServerInfos.class);
						info.put("oneServer",infos.getServers().get(0).getServer());
						
						String[] arr = infos.getServers().get(0).getServer().split(":");
						info.put("serverIp1", arr[0]);
						info.put("serverPort1", arr[1]);
						
						if(infos.getServers().size()>1){
							info.put("twoServer",infos.getServers().get(1).getServer());
							
							String[] arr2 = infos.getServers().get(1).getServer().split(":");
							info.put("serverIp2", arr2[0]);
							info.put("serverPort2", arr2[1]);
							
						}else{
							info.put("twoServer","未设置");
						}
					}
				}
				//设备逻辑号窗口号
				if(type.equals("2") || type.equals("all")){
					String posno = getPosNo();
					String winno = getWinNo();
					info.put("setPosno",posno);
					info.put("setWinno",winno);
				}
				
				//消费相关
				if(type.equals("3") || type.equals("all")){
					
					info.put("setReadMode",Constant.CARD_READ_MODE.get(getCardType()));//读卡模式
					info.put("setPrintcode",Constant.PRINT_CODE_STR.get(getPrintCodeVersion()));//编码
					String print_str = "";
					if(getConsumePrintMode().equals("0")){
						print_str = "不打印";
					}else if(getConsumePrintMode().equals("1")){
						print_str = "打印1张";
					}else if(getConsumePrintMode().equals("2")){
						print_str = "打印2张";
					}else{
						print_str = "";
					}
					info.put("setNeedPrint", print_str);//是否打印
					
					info.put("setPrintBill", getConsumePrintMode());//打印发票设置
					info.put("setPwdMode", getConsumePwdMode());//密码验证模式
					info.put("setPwdModeStr", getConsumePwdMode().equals("0")?"MD5密文":"明文");//密码验证模式
				}else if(type.equals("4") || type.equals("all")){
					
					info.put("sysTitle", getSysTitle());
					info.put("printTitle", getPrintTitle());
				}else if(type.equals("5") || type.equals("all")){
					info.put("curPrintcode",getPrintCodeVersion());//编码
				}
				
				info.put("is_success", "1");
			}catch(Exception e){
				e.printStackTrace();
				info.put("is_success", "0");
			}
			return JSON.toJSONString(info);
		}
		
		/**
		 * 控件测试页面
		 */
		@JavascriptInterface
		public void goTest() {
		
			mHandler.sendEmptyMessage(GO_DEMO_CONTROL);	
		}
		
		@JavascriptInterface
		public String saveUiTitle(String sysTitle,String printTitle) {
		
			try{
				editor.putString(Constant.CACHE_SYS_TITLE, sysTitle);
				editor.putString(Constant.CACHE_PRINT_TITLE, printTitle);
				
				editor.commit();
				
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
	}

}
